﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using ThuVien;
using System.IO;

namespace TranTekBE
{
    public partial class ProductMgmt : PageRequireLogin
    {
        private int PageCount
        {
            set
            {
                ViewState["PageCount"] = value;
            }
            get
            {
                return FunctionsUtils.ConvertToInt(ViewState["PageCount"], 1);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this.Page, typeof(Page), "LoadJS", "LoadJS();", true);
            this.Page.Form.DefaultButton = btnSearch.UniqueID;
            if (Page.IsPostBack == false)
            {
                this.GetListPageSize(ddlPageSize);

                this.LoadProducts();
            }
        }

        private void LoadProducts()
        {
            ltError.Text = string.Empty;
            try
            {
                int currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);
                int pageSize = FunctionsUtils.ConvertToInt(ddlPageSize.SelectedValue, FunctionsUtils.ConvertToInt(FunctionsUtils.GetConfigValue("PageSize"), 50));

                string sSearch = this.CreateSearchCondition();

                string[] names = new string[] { "condition", "nItemPage", "curpage", "sessionID", "sortBy", "sortDirect" };
                object[] values = new object[] { sSearch, pageSize, currPage, Session.SessionID, ddlSortBy.SelectedValue, ddlSortDirect.SelectedValue };

                DataSet ds = FunctionsUtils.Database.ExecuteStoredProcReturnDataSet("xp_product_getpage", names, values, false);

                //get Total Record de tinh page count
                //DataSet ds1 = FunctionsUtils.Database.ExecuteQuery(sSearch);

                //int pageCount = FunctionsUtils.PageCount(ds1.Tables[0].Rows.Count, pageSize);
                //this.PageCount = FunctionsUtils.PageCount(ds1.Tables[0].Rows.Count, pageSize);
                //ds1.Dispose();
                int recordCount = FunctionsUtils.ConvertToInt(ds.Tables[1].Rows[0]["NoOfRec"], 0);
                this.PageCount = FunctionsUtils.PageCount(recordCount, pageSize);

                currPage = FunctionsUtils.GetCurrPage(currPage, this.PageCount);
                ltPage.Text = string.Format("&nbsp;{0} of {1}&nbsp;", currPage, this.PageCount);
                txtGoPage.Text = currPage.ToString();

                SetButtonPageNavigationStatus(currPage, this.PageCount);

                //DataSet ds = FunctionsUtils.Database.ExecuteQuery(sSearch, currPage, pageSize);

                if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                {
                    rpProduct.DataSource = ds.Tables[0];
                    rpProduct.DataBind();
                    ltNoRecord.Visible = false;

                    if (this.PageCount == 1)
                    {
                        phPageNavigation.Visible = false;
                    }
                    else
                    {
                        phPageNavigation.Visible = true;
                    }
                }
                else
                {
                    rpProduct.DataSource = null;
                    rpProduct.DataBind();
                    ltNoRecord.Visible = true;
                    phPageNavigation.Visible = false;
                }
            }
            catch (Exception ex)
            {
                ltError.Text = ex.Message;
                log.WriteLog("Error in ProductMgmt (LoadProducts): {0} {1}", ex, ex.StackTrace);
            }
        }

        private string CreateSearchCondition()
        {
            //string sSearch = "Select * From Vw_Product Where ProductISN > 0 ";
            string sSearch = "ProductISN > 0 ";

            if (txtProductName.Text.Trim().Length > 0)
            {
                sSearch += string.Format("And proName like '%{0}%' ", FunctionsUtils.DoubleSingleQuote(txtProductName.Text.Trim()));
            }

            if (txtOnHandQty.Text.Trim().Length > 0)
            {
                sSearch += string.Format("And proOnHandQty {0} {1} ", ddlCompareOnHand.SelectedValue, txtOnHandQty.Text.Trim());
            }

            if (ddlStatus.SelectedValue.Length > 0)
            {
                sSearch += string.Format("And proStatus = '{0}' ", ddlStatus.SelectedValue);
            }

            if (txtProductDesc.Text.Trim().Length > 0)
            {
                sSearch += string.Format("And Categorys like '%{0}%' ", FunctionsUtils.DoubleSingleQuote(txtCategory.Text.Trim()));
            }

            if (txtPrice.Text.Trim().Length > 0)
            {
                sSearch += string.Format("And proPrice {0} {1} ", ddlComparePrice.SelectedValue, txtPrice.Text.Trim());
            }

            if (txtProductDesc.Text.Trim().Length > 0)
            {
                sSearch += string.Format("And proComment like '%{0}%' ", FunctionsUtils.DoubleSingleQuote(txtProductDesc.Text.Trim()));
            }

            //sSearch += string.Format("Order By {0} {1}", this.SortBy, this.SortDirect);
            //sSearch += string.Format("Order By {0} {1}", ddlSortBy.SelectedValue, ddlSortDirect.SelectedValue);

            return sSearch;
        }

        protected void btnClearSearch_Click(object sender, ImageClickEventArgs e)
        {
            txtProductName.Text = string.Empty;
            txtOnHandQty.Text = string.Empty;
            ddlCompareOnHand.SelectedIndex = 0;
            txtPrice.Text = string.Empty;
            ddlComparePrice.SelectedIndex = 0;
            ddlStatus.SelectedIndex = 0;
            txtCategory.Text = string.Empty;
            txtProductDesc.Text = string.Empty;
            this.LoadProducts();
        }

        protected void btnSearch_Click(object sender, ImageClickEventArgs e)
        {
            this.LoadProducts();
        }

        protected void Sort_Click(object sender, EventArgs e)
        {
            LinkButton lbt = sender as LinkButton;

            string CommandArgument = string.Empty;
            string css = string.Empty;
            if (lbt.CommandArgument.ToUpper() == "DESC")
            {
                CommandArgument = "ASC";
                css = "sortAsc";
            }
            else
            {
                CommandArgument = "DESC";
                css = "sortDesc";
            }

            //remove sort o cac link button khac
            this.RemoveSortCss();

            lbt.CommandArgument = CommandArgument;
            lbt.CssClass = "GridHeader " + css;
            //this.SortBy = lbt.CommandName;
            //this.SortDirect = CommandArgument;

            FunctionsUtils.SelectItemInControlList(ddlSortBy, lbt.CommandName, SelectBy.Value);
            FunctionsUtils.SelectItemInControlList(ddlSortDirect, CommandArgument, SelectBy.Value);

            this.LoadProducts();
        }

        protected void ControlClick_Command(object sender, CommandEventArgs e)
        {
            int currPage = 0;
            switch (e.CommandName)
            {
                case "Delete":
                    this.DeleteProducts(hdList.Value);
                    break;
                case "Sort":
                    //remove sort o cac link button khac
                    this.RemoveSortCss();

                    //FunctionsUtils.SelectItemInControlList(ddlSortBy, lbt.CommandName, SelectBy.Value);
                    //FunctionsUtils.SelectItemInControlList(ddlSortDirect, CommandArgument, SelectBy.Value);
                    //this.SetSortAtributeForLinkButton(ddlSortBy.SelectedValue, ddlSortDirect.SelectedValue);
                    //this.LoadCategories();
                    break;
                case "GoToPage":
                    this.LoadProducts();
                    break;
                case "GoToPrev":
                    currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);
                    if (currPage > 1)
                    {
                        currPage -= 1;
                    }
                    txtGoPage.Text = currPage.ToString();
                    this.LoadProducts();
                    break;
                case "GoToNext":
                    currPage = FunctionsUtils.ConvertToInt(txtGoPage.Text, 1);

                    if (currPage < this.PageCount)
                    {
                        currPage += 1;
                    }
                    txtGoPage.Text = currPage.ToString();
                    this.LoadProducts();
                    break;
            }
        }

        protected void ddlPageSize_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.LoadProducts();
        }

        private void SetButtonPageNavigationStatus(int currPage, int pageCount)
        {
            if (currPage == 1)
            {
                btnPrev.Enabled = false;
            }
            else
            {
                btnPrev.Enabled = true;
            }

            if (currPage == pageCount)
            {
                btnNext.Enabled = false;
            }
            else
            {
                btnNext.Enabled = true;
            }
        }

        //private void DeleteProducts()
        //{
        //    try
        //    {
        //        if (hdList.Value.Length > 0)
        //        {
        //            FunctionsUtils.Database.ExecuteStoredProcReturnObject("xp_product_muldel", new string[] { "lstProductISN" }, new object[] { hdList.Value });
        //            this.LoadProducts();
        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        ltError.Text = ex.Message;
        //    }
        //}

        private void DeleteProducts(string lstProductISN)
        {
            if (lstProductISN.Length > 0)
            {
                try
                {
                    string productImageDir = FunctionsUtils.GetConfigValue("ProductImageDir");
                    string[] arrProductISN = lstProductISN.Split(',');
                    for (int i = 0; i < arrProductISN.Length; i++)
                    {
                        //delete directory
                        Directory.Delete(Path.Combine(productImageDir, arrProductISN[i]), true);

                        //delete in database
                        FunctionsUtils.Database.ExecuteStoredProcReturnObject("xp_product_muldel", new string[] { "lstProductISN" }, new object[] { arrProductISN[i] });
                    }

                    //FunctionsUtils.Database.ExecuteStoredProcReturnObject("xp_product_muldel", new string[] { "lstProductISN" }, new object[] { lstProductISN });
                    this.LoadProducts();
                }
                catch (Exception ex)
                {
                    ltError.Text = ex.Message;
                    log.WriteLog("Error in ProductMgmt (DeleteProducts): {0} {1}", ex, ex.StackTrace);
                }
            }
        }

        protected void UpdatePanel_Load(object sender, EventArgs e)
        {
            string arg = Request.Form["__EVENTARGUMENT"];
            if (string.IsNullOrEmpty(arg)) return;

            if (arg.StartsWith("del") == true)
            {
                //ltError.Text = arg; //Request.Params.Get("__EVENTARGUMENT");
                this.DeleteProducts(arg.Replace("del", ""));
            }
        }

        public string GetProductAvatar(object productISN, object imageFileName)
        {
            //GetImageUrl(Eval("ProductISN"), Eval("Avatar"))
            //<img src="<%# GetImageUrl(Eval("ProductISN"), Eval("Avatar")) %>" alt="" />
            if (FunctionsUtils.IsNullOrEmpty(imageFileName) == true)
                return string.Empty;
            return string.Format("<img src='{0}' alt='' />", GetImageUrl(productISN, imageFileName));
        }

        //public string GetAvatarUrl(object productISN, object imageFileName)
        //{
        //    return string.Format("{0}{1}/{2}", FunctionsUtils.GetConfigValue("ProductImageUrl"), productISN, imageFileName);
        //}
    }
}
